package com.fivefu.core.skyeye.event.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fivefu.base.common.utils.date.DateUtils;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.skyeye.event.entity.DbAiRedisStream;
import com.fivefu.core.skyeye.event.entity.DbAiScene;
import com.fivefu.core.skyeye.event.services.*;
import com.fivefu.core.skyeye.event.vo.EventImageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SyncRedisStreamServiceImpl implements SyncRedisStreamService {

    @Autowired
    private DbAiRedisStreamService dbAiRedisStreamService;
    @Autowired
    private RedisStreamService redisStreamService;
    @Autowired
    private DbAiSceneService dbAiSceneService;
    @Autowired
    private DbAiEventService dbAiEventService;
    @Autowired
    private DbAiEventImageService dbAiEventImageService;

    /**
     * redis失败事件补录
     */
    @Override
    public void supplementFailEvent() {
        //查询redis队列消息读取表中所有未成功数据
        List<DbAiRedisStream> failList = dbAiRedisStreamService.queryRedisStreamListByStatus(0);
        //原事件编号和场景编号查询无结果需补录    也就是新增事件
        //判断失败事件集是否为空
        if (null != failList && failList.size() > 0) {
            //解析stream_value
            failList.forEach(dbAiRedisStream -> {
                JSONObject messageObj = JSON.parseObject(dbAiRedisStream.getStreamValue());
                if (StrUtils.isNull(messageObj.getString("mq_type"))) {
                    return;
                }
                String code = messageObj.getString("unique_code");//探头编号
                Long eventId = messageObj.getLong("event_id");//识别事件标识
                Integer cid = messageObj.getInteger("cid");//场景编号

                JSONObject imgObj = messageObj.getJSONObject("images");//违停识别图片
                EventImageBean image = redisStreamService.analyEventImage(imgObj);
                String time = image.getImageTime();//事件开始时间

                LocalDateTime startTime = DateUtils.parse(time, "yyyyMMddHHmmss");
                DbAiScene scene = dbAiSceneService.querySceneByCvId(cid);
                if (null == scene) {
                    return;
                }
                //编辑事件
                Long aieventId = dbAiEventService.editEventStartInfo(eventId, scene.getCode(), code, startTime);
                if (null != aieventId ) {
                    //添加图片
                    dbAiEventImageService.editEventImage(aieventId,image);
                }
                //修改redis队列消息读取表的状态
                dbAiRedisStreamService.updateRedisStreamStatus(aieventId,1);
            });
        }
    }

}
